/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * CreateTablesForm.java
 *
 * Created on May 5, 2012, 11:13:14 AM
 */
package Server.GUI;

import Server.BUS.DatabaseBUS;
import Server.DTO.Column;
import Server.DTO.Table;

import java.awt.event.ActionEvent;
import java.util.ArrayList;

import java.util.List;

import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JTabbedPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

/**
 *
 * @author Trung
 */
public final class CreateTablesForm extends javax.swing.JPanel {
	private DatabaseBUS dbBus;
	private Table tableDTO = new Table();
	private DefaultTableModel tables = new DefaultTableModel();

	private JTabbedPane tabpane;
	private JLabel lb_status;
	private String path;
        
        public CreateTablesForm()
        {
            initComponents();
            
            this.dbBus = new DatabaseBUS();
            this.tables = (DefaultTableModel) table.getModel();
        }

	/** Creates new form CreateTablesForm */
	public CreateTablesForm(JTabbedPane tabPane, String path, JLabel label) {
		initComponents();

		this.lb_status = label;
		this.tabpane = tabPane;
		this.path = path;
		this.dbBus = new DatabaseBUS();
		this.tables = (DefaultTableModel) table.getModel();
		tb_address.setText(path);
//                tb_tablename.addKeyListener(new KeyListener(){
//                    @Override
//                    public void keyType()
//                });

		insertRow();
	}

	/** Creates new form CreateTablesForm */
	public CreateTablesForm(JTabbedPane tabPane, String path,
			Table tableDTO, JLabel label) {
		initComponents();

		this.lb_status = label;
		this.tableDTO = tableDTO;
		this.tabpane = tabPane;
		this.path = path;
		dbBus = new DatabaseBUS();
		tables = (DefaultTableModel) table.getModel();

		showTable();
	}

	// /Support call save desgin table from outside
	public void save() {
		ActionEvent evt = null;
		bt_okActionPerformed(evt);
	}

	// /Get value into DesignTable_Tin to call save table with it
	public void saveTable() {//********		
		Table table = new Table();
		tableDTO.setName(tb_tablename.getText());
                
                List<Column> lstColumns = new ArrayList<Column>();
                for(int i = 0; i < this.table.getRowCount() - 1; i++)
                {
                    Column column = new Column();
                    column.setName(this.table.getValueAt(i, 0).toString());
                    column.setDataType(this.table.getValueAt(i, 1).toString());
                    if(this.table.getValueAt(i, 2).equals(true))
                    {
                        column.setAllowNull(true);
                    }
                    else
                        column.setAllowNull(false);
                    
                    if(this.table.getValueAt(i, 3).equals(true))
                    {
                        column.setIsPrimaryKey(true);
                    }
                    else
                        column.setIsPrimaryKey(false);  
                    
                    lstColumns.add(column);
                    
                }

		tableDTO.setColumns(lstColumns);

		dbBus.saveDesignTable(tableDTO, tb_address.getText());
                
                System.out.println("Save " + path);
	}

	// /Get DesignTable_Tin to show screen
	public void showTable() {
		lb_status.setText(tableDTO.getName() + "Table");
		tb_tablename.setText(tableDTO.getName());
		tb_address.setText(path);

		//List<Row_Tin> lstRow = new ArrayList<Row_Tin>();
                List<Column> lstColumns = new ArrayList<Column>();
                lstColumns = tableDTO.getColumns();
		//lstRow = tableDTO.getLstRows();
		int ColNumber = tableDTO.getColumns().size();

		for (int i = 0; i < ColNumber; i++) {
			tables.insertRow(table.getRowCount(),
					new Object[] { lstColumns.get(i).getName(),
							lstColumns.get(i).getDataType(),
							lstColumns.get(i).isAllowNull(),
							lstColumns.get(i).isIsPrimaryKey() });
		}

		insertRow();
	}

	// /Insert a new row in JTable
	public void insertRow() {
		TableColumn dataType = table.getColumnModel().getColumn(1);

		JComboBox comboBox = new JComboBox();
		comboBox.addItem("int");
		comboBox.addItem("varchar");

		dataType.setCellEditor(new DefaultCellEditor(comboBox));

		tables.insertRow(table.getRowCount(), new Object[] { "", "", true,
				false });
	}

	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
	// <editor-fold defaultstate="collapsed"
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jMenu1 = new javax.swing.JMenu();
        buttonGroup1 = new javax.swing.ButtonGroup();
        jLabel1 = new javax.swing.JLabel();
        tb_tablename = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        table = new javax.swing.JTable();
        bt_remove = new javax.swing.JButton();
        bt_ok = new javax.swing.JButton();
        bt_cancel = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        tb_address = new javax.swing.JTextField();

        jMenu1.setText("jMenu1");

        setAutoscrolls(true);
        setPreferredSize(new java.awt.Dimension(650, 323));

        jLabel1.setText("Table name");

        table.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Column Name", "Data Type", "Allow Nulls", "Primary Key"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.Object.class, java.lang.Boolean.class, java.lang.Boolean.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        table.setColumnSelectionAllowed(true);
        table.setDoubleBuffered(true);
        table.setDragEnabled(true);
        table.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tableMouseClicked(evt);
            }
        });
        table.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                tableKeyTyped(evt);
            }
        });
        jScrollPane1.setViewportView(table);
        table.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);

        bt_remove.setText("Delete");
        bt_remove.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_removeActionPerformed(evt);
            }
        });

        bt_ok.setText("OK");
        bt_ok.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_okActionPerformed(evt);
            }
        });

        bt_cancel.setText("Cancel");
        bt_cancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_cancelActionPerformed(evt);
            }
        });

        jLabel2.setText("Address");

        tb_address.setEditable(false);
        tb_address.setAutoscrolls(false);
        tb_address.setEnabled(false);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(tb_tablename, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(43, 43, 43)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(tb_address, javax.swing.GroupLayout.PREFERRED_SIZE, 215, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(bt_remove, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(95, 95, 95)
                        .addComponent(bt_ok, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(103, 103, 103)
                        .addComponent(bt_cancel, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(bt_remove, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(95, 95, 95)
                        .addComponent(bt_ok, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(103, 103, 103)
                        .addComponent(bt_cancel, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 480, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(33, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(tb_tablename, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tb_address, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 267, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bt_ok)
                    .addComponent(bt_remove)
                    .addComponent(bt_cancel))
                .addGap(34, 34, 34))
        );
    }// </editor-fold>//GEN-END:initComponents

	private void bt_cancelActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_bt_cancelActionPerformed
		// TODO add your handling code here:
		tabpane.remove(tabpane.getSelectedIndex());
		lb_status.setText("Design table is closed!");
	}// GEN-LAST:event_bt_cancelActionPerformed

	private void bt_okActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_bt_okActionPerformed
		// TODO add your handling code here:
		saveTable();
		lb_status.setText("Design table saved!");
                 NhapLieu.main(null);
	}// GEN-LAST:event_bt_okActionPerformed

	private void tableMouseClicked(java.awt.event.MouseEvent evt) {// GEN-FIRST:event_tableMouseClicked
		// TODO add your handling code here:
		if (table.getSelectedColumn() == 3) {
			if (table.getValueAt(table.getSelectedRow(), 3).toString()
					.compareTo("true") == 0) {
				table.setValueAt(false, table.getSelectedRow(), 2);
			}
		}

		if (table.getSelectedColumn() == 2) {
			if (table.getValueAt(table.getSelectedRow(), 3).toString()
					.compareTo("true") == 0) {
				table.setValueAt(false, table.getSelectedRow(), 2);
			}
		}

		// table.validate();
	}// GEN-LAST:event_tableMouseClicked

	private void bt_removeActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_bt_removeActionPerformed
		// TODO add your handling code here:
		if (table.getSelectedRow() != table.getRowCount() - 1) {
			tables.removeRow(table.getSelectedRow());
			lb_status.setText("Done");
		} else {
			lb_status.setText("You can't remove a empty row");
		}
	}// GEN-LAST:event_bt_removeActionPerformed

	private void tableKeyTyped(java.awt.event.KeyEvent evt) {// GEN-FIRST:event_tableKeyTyped
		// TODO add your handling code here:
		if (table.getSelectedRow() == table.getRowCount() - 1) {
			insertRow();
		}
	}// GEN-LAST:event_tableKeyTyped

            /**
     * @param args the command line arguments
     */
        
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bt_cancel;
    private javax.swing.JButton bt_ok;
    private javax.swing.JButton bt_remove;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable table;
    private javax.swing.JTextField tb_address;
    private javax.swing.JTextField tb_tablename;
    // End of variables declaration//GEN-END:variables
}
